package com.zgw.fireline.design.edit;

import java.util.ArrayList;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.wb.core.model.JavaInfo;
import org.eclipse.wb.core.model.ObjectInfo;

import com.zgw.fireline.design.Model.DatasetInfo;
import com.zgw.fireline.design.common.ExecutionUtils2;

/**
 * 系统数据源选择对话框
 * */
public class SysSourceSelectDialog extends TitleAreaDialog {
	private List listSource;
	private Table propertyTable;
	private ArrayList<DatasetInfo> sourcelists;
	private Text textexpr;
	private Button butExprCheck;
	private Text textDefault;
	private Button butDefault;

	private final Class<?> type;

	public DatasetInfo source;
	public String getterMethod;
	public String[] key = new String[1];
	public Object defaultVar; // 默认值

	/**
	 * Create the dialog.
	 * 
	 * @param parentShell
	 * @wbp.parser.constructor
	 */
	public SysSourceSelectDialog(Shell parentShell, JavaInfo root, Class<?> type) {
		super(parentShell);
		setShellStyle(SWT.MAX | SWT.RESIZE);
		setHelpAvailable(false);
		sourcelists = new ArrayList<DatasetInfo>();
		searchSourceInfo(root);
		this.type = type;
	}

	private void searchSourceInfo(ObjectInfo parent) {
		for (ObjectInfo i : parent.getChildren()) {
			if (i instanceof DatasetInfo) {
				if (!sourcelists.contains(i))
					sourcelists.add((DatasetInfo) i);
			} else {
				searchSourceInfo(i);
			}
		}
	}

	/**
	 * Create contents of the dialog.
	 * 
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		setMessage("选择一个系统数据源和属性");
		setTitle("数据获取");
		getShell().setText(type.getName());
		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);
		GridLayout gl_container = new GridLayout(1, false);
		gl_container.horizontalSpacing = 6;
		gl_container.marginRight = 2;
		gl_container.marginLeft = 2;
		gl_container.verticalSpacing = 6;
		gl_container.marginWidth = 0;
		container.setLayout(gl_container);
		container.setLayoutData(new GridData(GridData.FILL_BOTH));

		Group composite = new Group(container, SWT.NONE);
		composite.setText("数据值设置");
		GridLayout gl_composite = new GridLayout(2, false);
		composite.setLayout(gl_composite);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false,
				1, 1));

		butExprCheck = new Button(composite, SWT.CHECK);
		butExprCheck.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false,
				false, 1, 1));
		butExprCheck.setText("设置字符表达示");
		butExprCheck.setEnabled(String.class.equals(type));// 只有字符型才可以使用字符表达示
		butExprCheck.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				textexpr.setEnabled(butExprCheck.getSelection());
			}
		});
		textexpr = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.MULTI);
		textexpr.setEnabled(false);
		GridData gd_text = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_text.heightHint = 50;
		textexpr.setLayoutData(gd_text);

		butDefault = new Button(composite, SWT.CHECK);
		butDefault.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				textDefault.setEnabled(butDefault.getSelection());
			}
		});
		butDefault.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false,
				1, 1));
		butDefault.setText("设置默认值");

		textDefault = new Text(composite, SWT.BORDER);
		textDefault.setEnabled(false);
		textDefault.setToolTipText("当指定的值为空时读取设定默认值");
		textDefault.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		SashForm sashForm = new SashForm(container, SWT.NONE);
		sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));

		Composite comp = new Composite(sashForm, SWT.BORDER);
		GridLayout gl_comp = new GridLayout(2, false);
		gl_comp.marginHeight = 0;
		gl_comp.marginWidth = 0;
		gl_comp.horizontalSpacing = 0;
		gl_comp.verticalSpacing = 0;
		comp.setLayout(gl_comp);

		CLabel lblNewLabel = new CLabel(comp, SWT.NONE);
		lblNewLabel.setText("数据源：");

		ToolBar toolBar = new ToolBar(comp, SWT.FLAT | SWT.RIGHT);
		toolBar.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false,
				1, 1));

		ToolItem tltmNewItem = new ToolItem(toolBar, SWT.NONE);
		tltmNewItem.setText("编辑");

		ToolItem tltmNewItem_1 = new ToolItem(toolBar, SWT.NONE);
		tltmNewItem_1.setText("添加");

		Label label = new Label(comp, SWT.SEPARATOR | SWT.HORIZONTAL);
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2,
				1));
		listSource = new List(comp, SWT.NONE);
		listSource.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
				2, 1));
		listSource.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				buildProperty();
			}
		});
		Composite comp2 = new Composite(sashForm, SWT.BORDER);
		GridLayout gl_comp2 = new GridLayout(1, false);
		gl_comp2.marginHeight = 0;
		gl_comp2.marginWidth = 0;
		gl_comp2.horizontalSpacing = 0;
		gl_comp2.verticalSpacing = 0;
		comp2.setLayout(gl_comp2);

		CLabel lblNewLabel_1 = new CLabel(comp2, SWT.NONE);
		GridData gd_lblNewLabel_1 = new GridData(SWT.LEFT, SWT.CENTER, false,
				false, 1, 1);
		gd_lblNewLabel_1.verticalIndent = 2;
		gd_lblNewLabel_1.horizontalIndent = 2;
		lblNewLabel_1.setLayoutData(gd_lblNewLabel_1);
		lblNewLabel_1.setText("属性：");

		Label label_1 = new Label(comp2, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));
		int style = SWT.FULL_SELECTION;
		if (type.isArray()) {
			style |= SWT.CHECK | SWT.MULTI;
		}
		propertyTable = new Table(comp2, style);
		propertyTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		propertyTable.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				if (butExprCheck.getSelection()) {
					String p = (String) e.item.getData();
					textexpr.insert("${" + p + "}");
				} else {
					okPressed();
				}
			}
		});
		TableColumn tblclmnNewColumn = new TableColumn(propertyTable, SWT.NONE);
		tblclmnNewColumn.setWidth(109);
		tblclmnNewColumn.setText("名称");

		TableColumn tblclmnNewColumn_1 = new TableColumn(propertyTable,
				SWT.NONE);
		tblclmnNewColumn_1.setWidth(100);
		tblclmnNewColumn_1.setText("类型");

		TableColumn tblclmnNewColumn_2 = new TableColumn(propertyTable,
				SWT.NONE);
		tblclmnNewColumn_2.setWidth(100);
		tblclmnNewColumn_2.setText("长度");
		sashForm.setWeights(new int[] { 234, 339 });
		initializeData();
		return area;
	}

	private void initializeData() {
		for (DatasetInfo i : sourcelists) {
			listSource.add(i.getVariableSupport().getName());
			listSource.setData(i.getVariableSupport().getName(), i);
			if (i == source) {
				listSource.setSelection(listSource.getItemCount() - 1);
			}
		}
		buildProperty();
		if (key[0] != null) {
			for (TableItem i : propertyTable.getItems()) {
				if (key[0].equals(i.getData())) {
					propertyTable.setSelection(i);
				}
			}
		}
		butExprCheck.setSelection("getStringForExpr".equals(getterMethod)
				&& String.class.equals(type));
		if (butExprCheck.getSelection() && key != null) {
			textexpr.setText(key[0]);
			textexpr.setEnabled(true);
		}
		butDefault.setSelection(defaultVar != null);
		if (defaultVar != null) {
			textDefault.setText(String.valueOf(defaultVar));
			textDefault.setEnabled(true);
		}
		propertyTable.setFocus();
	}

	private void buildProperty() {
		if (listSource.getSelectionCount() <= 0)
			return;
		propertyTable.removeAll();
		DatasetInfo info = (DatasetInfo) listSource.getData(listSource
				.getSelection()[0]);
		// if (!info.isInstantiationData()) { // 未初始化
		// try {
		// info.updateData();
		// } catch (Exception e) {
		// Shell parent = Display.getDefault().getActiveShell();
		// IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,
		// null, e);
		// ErrorDialog.openError(parent, "异常", "无法加载数据列，数据源更新出异常", status);
		// }
		// }
		try {
			String[] columns = info.getDataColumns();
			if (columns != null) {
				for (String c : columns) {
					TableItem item = new TableItem(propertyTable, SWT.NONE);
					item.setText(c);
					item.setData(c);// 绑定列名
				}
			}
		} catch (Exception e) {
			ExecutionUtils2.openErrorDialog("未能获得数据集列", e);
		}
		if (propertyTable.getItemCount() > 0)
			propertyTable.setSelection(0);
	}

	/**
	 * Create contents of the button bar.
	 * 
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		Button button = createButton(parent, IDialogConstants.OK_ID,
				IDialogConstants.OK_LABEL, true);
		button.setText("确定");
		Button button_1 = createButton(parent, IDialogConstants.CANCEL_ID,
				IDialogConstants.CANCEL_LABEL, false);
		button_1.setText("取消");
	}

	@Override
	protected void okPressed() {
		if (listSource.getSelectionCount() > 0
				&& propertyTable.getSelectionCount() > 0) {
			source = (DatasetInfo) listSource
					.getData(listSource.getSelection()[0]);
			if (butExprCheck.getSelection()) {
				getterMethod = "getStringForExpr";
				key[0] = textexpr.getText();
			} else {
				getterMethod = "getValue";
				if (type.isArray()) {
					propertyTable.getSelection();
					ArrayList<String> list = new ArrayList<String>();
					for (TableItem item : propertyTable.getItems()) {
						if (item.getChecked()) {
							list.add((String) item.getData());
						}
					}
					key = list.toArray(new String[list.size()]);
				} else {
					key[0] = (String) propertyTable.getSelection()[0].getData();
				}
				if (butDefault.getSelection()) {
					if (String.class.equals(type)) {
						defaultVar = textDefault.getText();
					} else if (Boolean.class.equals(type)) {
						defaultVar = Boolean
								.parseBoolean(textDefault.getText());
					} else if (Long.class.equals(type)) {
						defaultVar = Long.parseLong(textDefault.getText());
					} else if (Integer.class.equals(type)) {
						defaultVar = Integer.parseInt(textDefault.getText());
					} else if (Object.class == type) {
						defaultVar = textDefault.getText();
					}
				}
			}

		}
		super.okPressed();
	}

	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(584, 527);
	}
}
